
#include <vector>
#include <string>
#include <string.h>

const std::vector<std::string> explode (const std::string &str, const char c) {

   std::vector<std::string> v;

   char sep[] = "," ;

   sep[0] = c;

   char *pch = strtok ((char *) str.c_str () ,  sep);

   while (pch != NULL) {
      v.push_back (std::string (pch));
      pch = strtok (NULL, sep);
   }

   return v;
}   


static std::vector<std::string> nada;

std::vector<std::vector<double>> readCSV (char *filename, char sep, int &nrow, int &ncol, bool flaghead = false, std::vector<std::string> &headers = nada) {

   std::vector<double> v;

   static std::vector<std::vector<double>> M;
    
   M.clear();

   FILE *arq = fopen(filename, "r");

   if (NULL == arq)
      return M;

   ncol = 0;

   char buf[500];

   if (flaghead) {
      char *nada = fgets (buf, sizeof(buf), arq);
      headers    = explode (buf, sep);
   }

   while (fgets (buf, sizeof(buf), arq)) {

      std::vector<std::string> res = explode (buf, sep);

      if (res.size() < 1) continue;

      for (auto word : res) {
         v.push_back (atof(word.c_str()));//std::stod (word, NULL));
      }

      M.push_back (v);

      if (!ncol) ncol = v.size();

      v.clear ();
   }

   fclose (arq);

   ncol = v.size();
   nrow = M.size();

   return M;

}


void writeCSV (char *filename, char sep, std::vector<std::vector<double>> M, int nrow, int ncol) {
    
   std::string s;

   FILE *arq = fopen(filename, "w");

   if (NULL == arq)
      return;

   char buf[500];

   for (auto r : M) {

      s = "";

      for (int c = 0; c < ncol; ++c) {

         s = s + std::to_string (r[c]);

         if (c < ncol) s = s + std::to_string(sep);
      }

      fputs (s.c_str(), arq);
   } 

   fclose (arq);

}


